<template>
  <div :class="formContainerClass">
    <a-row>
      <template v-for="(item, index) in schemas" :key="index">
        <a-col :span="getItemSpan(item)">
          <div class="detail-item">
            <div :class="['item-title', `${getLabelWidthClass(item)}`]" :title="item.label">
              {{ item.label + '： ' }}
            </div>
            <div v-if="item.isHtml" class="item-content">
              {{ detailFormData[item.field] }}
            </div>
            <div
              v-if="item.isCard"
              class="item-content"
              style="
                 {
                  'display':'block','padding-top': '10px';
                }
              "
            >
              <span v-if="!detailFormData[item.field]"></span>
              <link-table-card
                v-else
                disabled
                detail
                :value="detailFormData[item.field]"
                :valueField="item.dictCode"
                :textField="item.dictText"
                :tableName="item.dictTable"
                :multi="item.multi"
              />
            </div>
            <div v-if="item.isImage" class="item-content">
              <div class="ant-upload-list ant-upload-list-picture-card">
                <template v-for="(url, index) in detailFormData[item.field]" :key="index">
                  <div class="ant-upload-list-picture-card-container" style="{ 'margin-top': '8px' }">
                    <span>
                      <div
                        class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-picture-card"
                        :data-has-actions="true"
                      >
                        <div class="ant-upload-list-item-info">
                          <img :src="url" alt="图片不存在" class="ant-upload-list-item-image" />
                        </div>
                        <span class="ant-upload-list-item-actions">
                          <download-outlined @click="handleDownloadFile(url)" />
                          <eye-outlined @click="handleViewImage(item.field)" />
                        </span>
                      </div>
                    </span>
                  </div>
                </template>
              </div>
            </div>
            <div v-if="item.isFile" class="item-content">
              <div class="ant-upload-list ant-upload-list-text">
                <template v-for="(url, index) in detailFormData[item.field]" :key="index">
                  <div>
                    <span>
                      <div class="ant-upload-list-item ant-upload-list-item-done ant-upload-list-item-list-type-text">
                        <div class="ant-upload-list-item-info">
                          <span class="ant-upload-span">
                            <div class="ant-upload-text-icon">
                              <paper-clip-outlined />
                            </div>
                            <a :href="url" target="_blank" rel="noopener noreferrer" class="ant-upload-list-item-name">{{ getFilename(url) }}</a>
                            <span class="ant-upload-list-item-card-actions">
                              <download-outlined @click="handleDownloadFile(url)" />
                            </span>
                          </span>
                        </div>
                      </div>
                    </span>
                  </div>
                </template>
              </div>
            </div>
            <div v-else class="item-content">
              {{ detailFormData[item.field] }}
            </div>
          </div>
        </a-col>
      </template>
    </a-row>
  </div>
</template>
<script lang="ts">
  import { ref, computed, watch, defineComponent } from 'vue';
  import { propTypes } from '/@/utils/propTypes';
  import { getDictItemsByCode } from '/@/utils/dict';
  import { filterMultiDictText, filterDictText } from '/@/utils/dict/JDictSelectUtil';
  import { initDictOptions } from '/@/utils/dict/index';
  import { loadDictItem, queryDepartTreeSync, getUserList } from '/@/api/common/api';
  import { defHttp } from '/@/utils/http/axios';
  import { getAreaTextByCode } from '/@/components/Form/src/utils/Area';
  import { getFileAccessHttpUrl } from '/@/utils/common/compUtils';
  import { createImgPreview } from '/@/components/Preview/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { DownloadOutlined, EyeOutlined, PaperClipOutlined } from '@ant-design/icons-vue';
  import LinkTableCard from '../linkTable/LinkTableCard.vue';

  function useDetailForm(props) {
    console.log(props);
    const dictOptionsMap = {};
    const currentLinkFields = [];
    const detailFormData = ref({});
    const { createMessage } = useMessage();
    const formContainerClass = computed(() => {
      if (props.containerClass) {
        return `jeecg-detail-form ${props.containerClass}`;
      } else {
        return 'jeecg-detail-form';
      }
    });
    watch(
      () => props.data,
      async (formData) => {
        if (formData) {
          let arr = props.schemas;
          let temp = {};
          if (arr && arr.length > 0) {
            for (let item of arr) {
              let field = item.field;
              try {
                temp[field] = await getItemContent(item);
              } catch (e) {
                console.error('字段【' + field + '】文本获取失败', e);
              }
            }
          }
          detailFormData.value = temp;
        }
      },
      { deep: true, immediate: true }
    );
    async function getItemContent(item) {
      let formData = props.data;
      if (formData) {
        let value = formData[item.field];
        if (!value && value !== '0' && value !== 0) {
          return '';
        }
        let str = value;
        let view = item.view;
        if (view == 'list' || view == 'radio' || view == 'checkbox' || view == 'list_multi') {
          str = await getSelectText(item, formData);
        } else if (view == 'sel_search') {
          str = await getTableDataText(item, formData);
        } else if (view == 'cat_tree') {
          str = await getCategoryDataText(item, formData);
        } else if (view == 'link_table') {
          str = await getLinkTableData(item, formData);
        } else if (view == 'sel_depart') {
          str = await getDepartDataText(item, formData);
        } else if (view == 'sel_user') {
          str = await getUserDataText(item, formData);
        } else if (view == 'pca') {
          str = getAreaTextByCode(value);
        } else if (view == 'link_down') {
          str = await getLinkDownDataText(item, formData);
        } else if (view == 'sel_tree') {
          str = await getTreeDataText(item, formData);
        } else if (view == 'switch') {
          str = await getSwitchDataText(item, formData);
        } else if (view == 'image' || view == 'file') {
          str = getFileList(item, formData);
        } else {
          if (currentLinkFields.indexOf(item.field) >= 0) {
            let arr = dictOptionsMap[item.field];
            if (arr && arr.length > 0) {
              str = filterMultiDictText(arr, value);
            }
          }
        }
        return str;
      }
      return '';
    }
    async function getSelectText(item, formData) {
      let dictCode = getRequestDictCode(item);
      let value = formData[item.field];
      if (!dictCode) {
        return value;
      }
      let options = getDictItemsByCode(dictCode);
      if (options && options.length > 0) {
        return filterMultiDictText(options, value);
      } else {
        let dictRes = [];
        if (dictOptionsMap[dictCode]) {
          dictRes = dictOptionsMap[dictCode];
        } else {
          dictRes = (await initDictOptions(dictCode)) || [];
        }
        if (dictRes && dictRes.length > 0) {
          dictOptionsMap[dictCode] = dictRes;
          return filterMultiDictText(dictRes, value);
        }
      }
      return '';
    }
    function getRequestDictCode(item) {
      let temp = '';
      let { dictCode, dictTable, dictText } = item;
      if (!dictTable) {
        temp = dictCode;
      } else {
        temp = encodeURI(`${dictTable},${dictText},${dictCode}`);
      }
      return temp;
    }
    async function getTableDataText(item, formData) {
      let dictCode = getRequestDictCode(item);
      let value = formData[item.field];
      if (!value) {
        return '';
      }
      let arr = [];
      if (dictOptionsMap[dictCode + value]) {
        arr = dictOptionsMap[dictCode + value];
      } else {
        arr = (await defHttp.get({ url: `api-upms/sys/dict/loadDictItem/${dictCode}`, params: { key: value } })) || [];
      }
      if (arr && arr.length > 0) {
        dictOptionsMap[dictCode + value] = arr;
        return arr.join(',');
      }
      return '';
    }
    async function getCategoryDataText(item, formData) {
      let value = formData[item.field];
      if (!value) {
        return '';
      }
      let arr = (await loadDictItem({ ids: value })) || [];
      if (arr && arr.length > 0) {
        return arr.join(',');
      }
      return '';
    }
    async function getDepartDataText(item, formData) {
      let value = formData[item.field];
      if (!value) {
        return '';
      }
      let extend = getExtendConfig(item);
      let storeField = extend.store || 'id';
      let arr = (await queryDepartTreeSync({ ids: value, primaryKey: storeField })) || [];
      if (arr && arr.length > 0) {
        let temp = [];
        for (let item2 of arr) {
          temp.push(item2.title);
        }
        return temp.join(',');
      }
      return '';
    }
    async function getUserDataText(item, formData) {
      let value = formData[item.field];
      if (!value) {
        return '';
      }
      let extend = getExtendConfig(item);
      let storeField = extend.store || 'username';
      let params = {
        [storeField]: value,
      };
      let res = (await getUserList(params)) || {};
      let arr = res.records || [];
      if (arr && arr.length > 0) {
        let temp = [];
        console.log('getUserDataText', arr);
        let textField = extend.text || 'realname';
        for (let item2 of arr) {
          temp.push(item2[textField]);
        }
        return temp.join(',');
      }
      return '';
    }
    function getExtendConfig(item) {
      let extend = {};
      let { fieldExtendJson } = item;
      if (fieldExtendJson) {
        if (typeof fieldExtendJson == 'string') {
          try {
            let json = JSON.parse(fieldExtendJson);
            extend = Object.assign({}, json);
          } catch (e) {
            console.error(e);
          }
        }
      }
      return extend;
    }
    async function getLinkDownDataText(item, formData) {
      let { dictTable, field } = item;
      let arr = [];
      if (dictOptionsMap[field]) {
        arr = dictOptionsMap[field];
      } else {
        if (dictTable) {
          let json = JSON.parse(dictTable);
          if (json) {
            let { table, txt, key, linkField } = json;
            let dictCode = `${table},${txt},${key}`;
            let temp = (await initDictOptions(dictCode)) || [];
            arr = [...temp];
            if (arr && arr.length > 0) {
              dictOptionsMap[field] = arr;
              if (linkField) {
                let fieldArray = linkField.split(',');
                for (let item2 of fieldArray) {
                  dictOptionsMap[item2] = arr;
                  currentLinkFields.push(item2);
                }
              }
            }
          }
        }
      }
      if (arr && arr.length > 0) {
        let value = formData[field];
        return filterMultiDictText(arr, value);
      }
      return '';
    }
    async function getTreeDataText(item, formData) {
      let { dict, field } = item;
      let arr = [];
      if (dictOptionsMap[field]) {
        arr = dictOptionsMap[field];
      } else {
        if (dict) {
          arr = await initDictOptions(dict);
        }
      }
      if (arr && arr.length > 0) {
        let value = formData[field];
        return filterMultiDictText(arr, value);
      }
      return '';
    }
    async function getSwitchDataText(item, formData) {
      let { fieldExtendJson, field } = item;
      let options = ['Y', 'N'];
      if (fieldExtendJson) {
        options = JSON.parse(fieldExtendJson);
      }
      let arr = [
        { value: options[0], text: '是' },
        { value: options[1], text: '否' },
        { value: options[0] + '', text: '是' },
        { value: options[1] + '', text: '否' },
      ];
      let value = formData[field];
      return filterDictText(arr, value);
    }
    function getItemSpan(item) {
      if (item.span) {
        return item.span;
      }
      return props.span;
    }
    function getFileList(item, formData) {
      let str = formData[item.field];
      if (!str) {
        return [];
      }
      let arr = str.split(',');
      let result = [];
      for (let item2 of arr) {
        let src = getFileAccessHttpUrl(item2) || '';
        if (src) {
          result.push(src);
        }
      }
      return result;
    }
    function handleDownloadFile(url) {
      if (url) {
        window.open(url);
      }
    }
    function handleViewImage(field) {
      let values = detailFormData.value[field];
      if (!values || values.length == 0) {
        createMessage.warning('无图片!');
        return;
      }
      createImgPreview({ imageList: values });
    }
    function getFilename(url) {
      if (!url) {
        return '';
      }
      return url.substring(url.lastIndexOf('/') + 1);
    }
    const span24ViewArray = ['file', 'image', 'markdown', 'umeditor'];
    function getLabelWidthClass(item) {
      if (span24ViewArray.indexOf(item.view) >= 0) {
        if (props.span == 12) {
          return 'span12';
        } else if (props.span == 8) {
          return 'span8';
        } else if (props.span == 6) {
          return 'span6';
        } else {
          return 'span24';
        }
      }
      return '';
    }
    async function getLinkTableData(item, formData) {
      let value = formData[item.field];
      let extend = getExtendConfig(item);
      if (extend.showType == 'select') {
        if (!value) {
          return '';
        }
        return formData[item.field + '_dictText'];
      } else {
        if (!value) {
          return '';
        }
        return formData[item.field];
      }
    }
    return {
      formContainerClass,
      detailFormData,
      getItemSpan,
      handleDownloadFile,
      handleViewImage,
      getFilename,
      getLabelWidthClass,
    };
  }

  export default defineComponent({
    name: 'DetailForm',
    components: {
      DownloadOutlined,
      EyeOutlined,
      PaperClipOutlined,
      LinkTableCard,
    },
    props: {
      span: propTypes.number.def(24),
      schemas: propTypes.array.def([]),
      data: propTypes.object.def({}),
      containerClass: propTypes.string.def(''),
    },
    setup(props) {
      const { formContainerClass, detailFormData, getItemSpan, handleDownloadFile, handleViewImage, getFilename, getLabelWidthClass } =
        useDetailForm(props);
      return {
        formContainerClass,
        detailFormData,
        getItemSpan,
        handleDownloadFile,
        handleViewImage,
        getFilename,
        getLabelWidthClass,
      };
    },
  });
</script>
<style scoped>
  .jeecg-detail-form {
    border: 1px solid #f0f0f0;
    border-left: none;
    border-bottom: none;
  }

  .jeecg-detail-form .detail-item {
    display: flex;
    flex-direction: row;
    align-items: stretch;
    line-height: 24px;
    border-bottom: 1px solid #f0f0f0;
    height: 100%;
  }

  .jeecg-detail-form .detail-item .item-title {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    flex-shrink: 0;
    flex-grow: 0;
    min-width: 100px;
    width: 24%;
    max-width: 220px;
    background-color: #fafafa;
    border-right: 1px solid #f0f0f0;
    padding: 10px 0;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
  }

  .jeecg-detail-form .detail-item .item-title.span24 {
    width: 24%;
  }

  .jeecg-detail-form .detail-item .item-title.span12 {
    width: 12%;
  }

  .jeecg-detail-form .detail-item .item-title.span8 {
    width: 8%;
  }

  .jeecg-detail-form .detail-item .item-title.span6 {
    width: 6%;
  }

  .jeecg-detail-form .detail-item .item-content {
    border-right: 1px solid #f0f0f0;
    flex-grow: 1;
    padding-left: 10px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }

  .jeecg-detail-form .detail-item .item-content .anticon:hover {
    color: #40a9ff;
  }

  .jeecg-detail-form .detail-item .item-content .detail-image-container {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
    color: #000000d9;
    font-size: 14px;
    font-variant: tabular-nums;
    list-style: none;
    font-feature-settings: 'tnum';
    line-height: 1.5715;
  }

  .jeecg-detail-form .detail-item .item-content .detail-image-container .image-item {
    display: inline-block;
    width: 104px;
    height: 104px;
    margin: 5px;
    border: 1px solid #f0f0f0;
    vertical-align: top;
  }
</style>
